//
//  facebook.m
//  shareTest
//
//  Created by Jacob on 14/10/22.
//  Copyright (c) 2014年 com.sxiaojian. All rights reserved.
//

#import "FaceBook.h"
#import <FacebookSDK/FacebookSDK.h>
#import "PlatformUserMoidel.h"
@interface FaceBook ()

@property (nonatomic,strong) void (^successBlock)(PlatformUserMoidel *model);
@property (nonatomic,strong) void (^failedBlock)(NSString *message);
@property (nonatomic,strong) NSString *token;
@property (nonatomic,strong) void (^shareSuccess)(bool isSuccess);

@property (strong, nonatomic) NSDictionary *refererAppLink;
@end

@implementation FaceBook


+(instancetype)shareInstance
{
    static FaceBook *fb = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        fb = [[super alloc] init];
    }) ;
    return fb;
}
-(instancetype) init
{
    self = [super init];
    if (self) {
        [self setUp];
    }
    return self;
}
-(void)setUp
{
   [FBAppEvents activateApp];
}
-(BOOL)openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [FBSession.activeSession setStateChangeHandler:
     ^(FBSession *session, FBSessionState state, NSError *error) {
         

         [self sessionStateChanged:session state:state error:error];
     }];
    BOOL urlWasHandled =
    [FBAppCall handleOpenURL:url
           sourceApplication:sourceApplication
             fallbackHandler:
     ^(FBAppCall *call) {
         // Parse the incoming URL to look for a target_url parameter
         NSString *query = [url query];
         NSDictionary *params = [self parseURLParams:query];
         // Check if target URL exists
         NSString *appLinkDataString = [params valueForKey:@"al_applink_data"];
         if (appLinkDataString) {
             NSError *error = nil;
             NSDictionary *applinkData =
             [NSJSONSerialization JSONObjectWithData:[appLinkDataString dataUsingEncoding:NSUTF8StringEncoding]
                                             options:0
                                               error:&error];
             if (!error &&
                 [applinkData isKindOfClass:[NSDictionary class]] &&
                 applinkData[@"target_url"]) {
                 self.refererAppLink = applinkData[@"referer_app_link"];
                 NSString *targetURLString = applinkData[@"target_url"];
                 // Show the incoming link in an alert
                 // Your code to direct the user to the
                 // appropriate flow within your app goes here
                 [[[UIAlertView alloc] initWithTitle:@"Received link:"
                                             message:targetURLString
                                            delegate:nil
                                   cancelButtonTitle:@"OK"
                                   otherButtonTitles:nil] show];
             }
         }
     }];
    
    return urlWasHandled;

//    return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];

}
- (NSDictionary*)parseURLParams:(NSString *)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val = [[kv objectAtIndex:1]
                         stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [params setObject:val forKey:[kv objectAtIndex:0]];
    }
    return params;
}
-(void)bindSuccess:(void (^)(PlatformUserMoidel *))success error:(void (^)(NSString *))errorBlock
{
   
    self.successBlock = [success copy];
    self.failedBlock = [errorBlock copy];
        // Close the session and remove the access token from the cache
        // The session state handler (in the app delegate) will be called automatically
        [FBSession.activeSession closeAndClearTokenInformation];
        
        // Open a session showing the user the login UI
        // You must ALWAYS ask for public_profile permissions when opening a session
        [FBSession openActiveSessionWithReadPermissions:@[@"public_profile"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {
             
             // Retrieve the app delegate
             // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
             [self sessionStateChanged:session state:state error:error];
         }];
    
  
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
    // If the session was opened successfully
    if (!error && state == FBSessionStateOpen){
        NSLog(@"Session opened");
        // Show the user the logged-in UI
        [self userLoggedIn];
        return;
    }
    if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
        // If the session is closed
        NSLog(@"Session closed");
        // Show the user the logged-out UI
        [self userLoggedOut];
    }
    
    // Handle errors
    if (error){
        NSLog(@"Error");
        NSString *alertText;
        NSString *alertTitle;
        // If the error requires people using an app to make an action outside of the app in order to recover
        if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
            alertTitle = @"Something went wrong";
            alertText = [FBErrorUtility userMessageForError:error];
//            [self showMessage:alertText withTitle:alertTitle];
        } else {
            
            // If the user cancelled login, do nothing
            if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
                NSLog(@"User cancelled login");
                
                // Handle session closures that happen outside of the app
            } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession){
                alertTitle = @"Session Error";
                alertText = @"Your current session is no longer valid. Please log in again.";
//                [self showMessage:alertText withTitle:alertTitle];
                
                // Here we will handle all other errors with a generic error message.
                // We recommend you check our Handling Errors guide for more information
                // https://developers.facebook.com/docs/ios/errors/
            } else {
                //Get more error information from the error
                NSDictionary *errorInformation = [[[error.userInfo objectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:@"body"] objectForKey:@"error"];
                
                // Show the user an error message
                alertTitle = @"Something went wrong";
                alertText = [NSString stringWithFormat:@"Please retry. \n\n If the problem persists contact us and mention this error code: %@", [errorInformation objectForKey:@"message"]];
//                [self showMessage:alertText withTitle:alertTitle];
            }
        }
        // Clear this token
        [FBSession.activeSession closeAndClearTokenInformation];
        // Show the user the logged-out UI
        [self userLoggedOut];
    }
}
-(void)userLoggedOut
{

}
-(void)userLoggedIn
{
    [FBSession openActiveSessionWithReadPermissions:@[@"public_profile",@"user_friends"]
                                       allowLoginUI:YES
                                  completionHandler:
     ^(FBSession *session, FBSessionState state, NSError *error) {
         
         [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
             
             PlatformUserMoidel *model = [PlatformUserMoidel new];
             //        FBGraphObject *FBobj = result;
             model.userId = result[@"id"];
             model.avatar = result[@"link"];
             if ([result[@"gender"] isEqualToString:@"male"]) {
                 model.gender = @"男";
             }
             if ([result[@"gender"] isEqualToString:@"female"]) {
                 model.gender = @"女";
             }
             model.nickname = [NSString stringWithFormat:@"%@%@",result[@"last_name"],result[@"first_name"]];
             model.orginalData = result;
             void (^successBlock)(PlatformUserMoidel *model) = [self.successBlock copy];
             if (successBlock) {
                 successBlock(model);
             }
             
         }];

     }];
    
}
-(void)getFriendships:(void (^)(BOOL, NSArray *))block
{
     [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
         
         NSArray* friends = [result objectForKey:@"data"];
         block(YES,friends);
     }];
}
-(void)shareImage:(UIImage *)image title:(NSString *)title description:(NSString *)description andImageUrl:(NSString *)ImgUrl andurl:(NSString *)url andCompletionBlock:(void (^)(BOOL isSuccess))block
{
    [self ShareWithAPICallsImage:image title:title description:description andImageUrl:ImgUrl andurl:url andCompletionBlock:block];
  
}
- (void)ShareWithAPICallsImage:(UIImage *)image title:(NSString *)title description:(NSString *)description andImageUrl:(NSString *)ImgUrl andurl:(NSString *)url andCompletionBlock:(void (^)(BOOL isSuccess))block {

    FBShareDialogParams *para = [[FBShareDialogParams alloc] init];
    para.link = [NSURL URLWithString:url];
    para.name = title;
    para.caption = description;
    para.picture = [NSURL URLWithString:ImgUrl];
    // If the Facebook app is installed and we can present the share dialog
    if ([FBDialogs canPresentShareDialogWithParams:para]) {
        // Present the share dialog
        [FBDialogs presentShareDialogWithLink:para.link
                                         name:para.name
                                      caption:para.caption
                                  description:para.caption
                                      picture:para.picture
                                  clientState:nil
                                      handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                          if(error) {
                                              // An error occurred, we need to handle the error
                                              // See: https://developers.facebook.com/docs/ios/errors
                                              
                                              block(NO);
                                          } else {
                                              // Success
                                              NSLog(@"result %@", results);
                                              block(YES);
                                          }
                                      }];
    } else {
        // Present the feed dialog
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       title, @"name",
                                       description, @"caption",
                                       description, @"description",
                                       url, @"link",
                                       ImgUrl, @"picture",
                                       nil];
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:params
                                                  handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                                                      if (error) {
                                                          // An error occurred, we need to handle the error
                                                          // See: https://developers.facebook.com/docs/ios/errors
                                                          block(NO);
                                                      } else {
                                                          if (result == FBWebDialogResultDialogNotCompleted) {
                                                              // User cancelled.
                                                              NSLog(@"User cancelled.");
                                                              block(NO);
                                                          } else {
                                                              // Handle the publish feed callback
                                                              NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
                                                              
                                                              if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User cancelled.
                                                                  NSLog(@"User cancelled.");
                                                                  block(NO);
                                                                  
                                                              } else {
                                                                  // User clicked the Share button
                                                                  NSString *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                  NSLog(@"result %@", result);
                                                                  block(YES);
                                                              }
                                                          }
                                                      }
                                                  }];
    }
 
}


@end
